/*
 * Copyright 2012 Alain Pannetrat (L1L1@gmx.com)
 * 
 * This file is part of cookie-miner.
 * 
 * cookie-miner is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * cookie-miner is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with cookie-miner. If not, see http://www.gnu.org/licenses/.
 *
 * @version: $Id$
 *
 */
//#include "configuration.h"
#include "http_proxy.h"
#include "log_facility.h"
#include <openssl/ssl.h>
#ifdef _WIN32
#include <signal.h>
#else
#include <sys/signal.h>
#endif

void sigint_handler(int sig)
{
    logger.message(logger.LOG_WARNING,"Caught SIGINT... stopping");
    close(2);
    close(1);
    exit(0);
}

void sigsegv_handler(int sig)
{
    logger.message(logger.LOG_ERROR,"ALERT! Caught SIGSEGV... stopping");
    close(2);
    close(1);
    exit(0);
}

int main(int argc, char **argv)
{
	Json::Value* config = Json::create_object();
	HttpProxy proxy(config);
	int opt;

	config->object("proxy")->set("port",9999);

	while ((opt=getopt(argc,argv,"hp:VSl:")) != -1)
	{
		switch (opt) {
			case 'p':
				config->object("proxy")->set("port",atoi(optarg));
				break;
			case 'V':
				fprintf(stderr, VERSION_ID "\n");
				exit(0);
				break;
			case 'S':
				config->object("proxy")->object("ssl")->set("save_certificates",true);
				break;
			case 'l':
				config->object("proxy")->set("content_length_limit",atoi(optarg));
				break;
			case 'h':
			default:
				fprintf(stderr,"This tool is (c) Alain Pannetrat, licenced under the GPL version 3.\n\n");
				fprintf(stderr,"usage: proxy [-p port] [-x extra_proxy_host:extra_proxy_port] [-V] [-S] [-d] [-l bytes]\n");
				fprintf(stderr,"       -V: print version\n");
				fprintf(stderr,"       -S: save collected ssl certificates\n");
				fprintf(stderr,"       -l: limit saved content length to 'bytes'\n");
				fprintf(stderr," default port is 9999.\n\n");
				exit(EXIT_FAILURE);
		}
	}

	SSL_library_init();
	SSL_load_error_strings();
	OpenSSL_add_all_algorithms();

	signal(SIGINT,sigint_handler);
	signal(SIGSEGV,sigsegv_handler);


	logger.message(logger.LOG_DEBUG,"Started proxy version %s",VERSION_ID);

	if (!proxy.run()) logger.message(logger.LOG_ERROR,"Failed to run proxy, stoping.");
	
	return 0;
}

